package com.gitee.jjnnzb.designpatterninspring.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jjn
 * @since 2021-10-27 9:20
 */
@Slf4j
@Component
public class JwtTokenUtil {
    private static final String SYSTEM = "system";
    private static final String USER_NAME = "username";
    private static final String USER_ID = "userId";
    private static final String CLIENT_ID = "clientId";
    private static final String ORG_ID = "orgId";
    private static final String JOBS = "authorities";
    
    public static String getParam(String token, String param) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(param).asString();
        } catch (JWTDecodeException var3) {
            return null;
        }
    }
    
    public static List<String> getList(String token, String param) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(param).asList(String.class);
        } catch (JWTDecodeException var3) {
            return new ArrayList<>(10);
        }
    }
    
    public static String getSystemCode(String token) {
        return getParam(token, SYSTEM);
    }
    
    public static String getClientId(String token) {
        return getParam(token, CLIENT_ID);
    }
    
    public static String getUserName(String token) {
        return getParam(token, USER_NAME);
    }
    
    public static String getUserId(String token) {
        return getParam(token, USER_ID);
    }
    
    public static String getOrgId(String token) {
        return getParam(token, ORG_ID);
    }
    
    public static List<String> getJobs(String token) {
        return getList(token, JOBS);
    }
}
